package middleware

import (
	"cloud-disk/global/define"
	"cloud-disk/util"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v4"
)

func Auth() gin.HandlerFunc {
	return func(c *gin.Context) {
		tokenString := c.GetHeader("Authorization")
		token, err := jwt.ParseWithClaims(tokenString, &util.UserClaim{}, func(token *jwt.Token) (interface{}, error) {
			return []byte(define.Conf.Token.Key), nil
		})
		if err != nil {
			fmt.Println("token valid fail")
			c.Abort()
			return
		}
		if claims, ok := token.Claims.(*util.UserClaim); ok && token.Valid {
			c.Set("id", claims.Id)
			c.Set("identity", claims.Identity)
			c.Set("email", claims.Email)
			c.Next()
		} else {
			fmt.Println("token valid fail")
			c.Abort()
		}
	}
}
